<template>
  <div style="width: 100%">
    <div ref="chartContainer" :style="{ width: width, height: height }" />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { reactive } from "vue";
const chartContainer = ref(Math.random().toString(36).slice(2, 10));
// const echartsRef = ref < string > Math.random().toString(36).slice(2, 10);
let chartInstance = null;
const props = defineProps({
  width: {
    type: String,
    default: ""
  },
  height: {
    type: String,
    default: ""
  },
  option: {
    type: Object,
    required: true
  },
  type: {
    type: String,
    default: ""
  }
});
const legendDoms = ref(null);
onMounted(() => {
  setTimeout(() => {
    initChart();
  }, 100);
  window.addEventListener("resize", handelResize);
});
const handelResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
nextTick(() => {
  initChart();
});
const initChart = () => {
  if (chartContainer.value) {
    if (props.type == "dark") {
      chartInstance = echarts.init(chartContainer.value, "dark");
      const lendom = legendDoms.value;
      chartInstance.setOption(props.option, true);
    } else {
      chartInstance = echarts.init(chartContainer.value);
      const lendom = legendDoms.value;
      chartInstance.setOption(props.option, true);
    }
  }
};
watch(
  () => props.option,
  newOption => {
    // console.log(newOption);
    if (chartInstance) {
      chartInstance.setOption(newOption, true);
    }
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
  window.removeEventListener("resize", handelResize);
});
</script>

<style scoped lang="scss">
.legendDoms {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  height: 300px;
  background: white;
}
</style>
